<?php

namespace App\Http\Controllers\Dn;

use App\Http\Controllers\Controller;
use App\Http\Requests\Dn\ShopClassRequest;
use App\Models\DnShopClass;
use Illuminate\Http\Request;
use Validator;

class GoodsClassController extends Controller
{
    public function index(Request $request, DnShopClass $shopClass)
    {
        $limit = $request->input('limit', 20);
        if (!empty($limit)) {
            $data = $shopClass->paginate();
            // dd(get_class_methods($data));
            return $this->jsonOk(['list' => $this->toArray($data->items()), 'total' => $data->total()]);
        } else {
            $data = $shopClass->all();
            return $this->jsonOk(['list' => $data->toArray(), 'total' => $data->count()]);
        }
    }

    public function create(ShopClassRequest $request, DnShopClass $shopClass)
    {
        $shopClass->class_name = $request->class_name;
        $shopClass->class_photo = $request->class_photo;
        $shopClass->sort = $request->sort;

        $shopClass->zt = 0;

        $shopClass->save();

        return $this->jsonOk([], '添加成功');
    }

    public function update(ShopClassRequest $request, DnShopClass $shopClass)
    {
        $shopClass = DnShopClass::find($request->input('class_id'));
        $shopClass->class_name = $request->class_name;
        $shopClass->class_photo = $request->class_photo;
        $shopClass->sort = $request->sort;

        $shopClass->save();

        return $this->jsonOk([], '更新成功');
    }

    public function delete(Request $request, DnShopClass $shopClass)
    {
        $shopClass = DnShopClass::find($request->input('class_id'));
        $shopClass->delete();
        return $this->jsonOk([], '删除成功');
    }

    public function switch(Request $request, DnShopClass $shopClass)
    {
        $shopClass = DnShopClass::find($request->input('class_id'));
        $shopClass->zt ^= 1;
        $shopClass->save();

        return $this->jsonOk([], '切换成功');
    }

    private function toArray(array $data)
    {
        return array_map(function ($item) {
            return $item->toArray();
        }, $data);
    }
}
